<template>
    <view class="container">
        <view class="tui-refund-list">
            <scroll-view scroll-y="true" class="refund-scroll" :refresher-enabled="true" :refresher-triggered="refresherTriggered" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore" lower-threshold="120">
                <!-- 动态渲染退款申请 -->
                <view class="tui-refund-item" v-for="(refund, refundIndex) in refunds" :key="refundIndex">
                    <tui-list-cell :hover="false" lineLeft="0">
                        <view class="tui-refund-header">
                            <view class="tui-refund-info">
                                <view class="tui-refund-number">退款单号：{{ refund.no }}</view>
                                <view class="tui-refund-time">申请时间：{{ formatRefundCreateTime(refund.createTime) }}</view>
                            </view>
                            <view class="tui-refund-status">
                                <view class="tui-refund-status-content">
                                    {{ getRefundStatusText(refund.status) }}
                                </view>
                            </view>
                        </view>
                    </tui-list-cell>
                    
                    <!-- 商品信息 -->
                    <tui-list-cell padding="0" @click="viewRefundDetail(refund.id)">
                        <view class="tui-goods-item">
                            <image :src="refund.picUrl" class="tui-goods-img"></image>
                            <view class="tui-goods-center">
                                <view class="tui-goods-name">{{ refund.spuName }}</view>
                                <view class="tui-goods-attr">
                                    <span v-for="property in refund.properties" :key="property.propertyId">
                                        {{ property.propertyName }}: {{ property.valueName }}
                                    </span>
                                </view>
                            </view>
                            <view class="tui-price-right">
                                <view>￥{{ (refund.refundPrice / 100).toFixed(2) }}</view>
                                <view>x{{ refund.count }}</view>
                            </view>
                        </view>
                    </tui-list-cell>
                    
                    <tui-list-cell :hover="false" unlined>
                        <view class="tui-refund-info-detail">
                            <view class="tui-refund-type">
                                <text>{{ refund.way === 10 ? '仅退款' : '退款退货' }}</text>
                            </view>
                            <view class="tui-refund-reason">
                                <text>申请原因：{{ refund.applyReason }}</text>
                            </view>
                            <view class="tui-refund-status-desc">
                                <text>{{ getRefundStatusDescription(refund) }}</text>
                            </view>
                            <view v-if="refund.applyDescription" class="tui-refund-description">
                                <text>申请说明：{{ refund.applyDescription }}</text>
                            </view>
                        </view>
                    </tui-list-cell>
                    
                    <!-- 操作按钮 -->
                    <view class="tui-refund-btn">
                        <view class="tui-btn-ml">
                            <tui-button type="info" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                @click="viewRefundDetail(refund.id)">查看详情</tui-button>
                        </view>
                        <view class="tui-btn-ml" v-if="refund.status === 10">
                            <tui-button type="black" plain width="152rpx" height="56rpx" :size="26" shape="circle"
                                @click="cancelRefund(refund.id)">取消申请</tui-button>
                        </view>
                    </view>
                </view>
                
                <tui-loadmore v-if="loading" :index="3" type="red"></tui-loadmore>
                <tui-nomore v-if="!hasMore" backgroundColor="#fafafa"></tui-nomore>
            </scroll-view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                refunds: [], // 退款数据
                pageIndex: 1, // 当前页码
                pageSize: 10, // 每页数量
                hasMore: true, // 是否还有更多数据
                loading: false, // 是否在加载中
                scrollTop: 0,
                refresherTriggered: false, // 下拉刷新状态
            };
        },
        methods: {
            resetData() {
                this.refunds = [];
                this.pageIndex = 1;
                this.hasMore = true;
            },
            // 下拉刷新
            onRefresh() {
                if (this.refresherTriggered) return;
                this.refresherTriggered = true;
                this.resetData();
                this.fetchRefunds(true);
            },
            // 上拉加载
            onLoadMore() {
                if (!this.hasMore || this.loading) return;
                this.pageIndex++;
                this.fetchRefunds();
            },
            // 查看退款详情
            viewRefundDetail(refundId) {
                uni.navigateTo({
                    url: `../refundDetail/refundDetail?id=${refundId}`
                });
            },
            // 取消退款申请
            cancelRefund(id) {
                uni.showModal({
                    title: "确认取消",
                    content: "您确定要取消退款申请吗？",
                    success: (res) => {
                        if (res.confirm) {
                            this.$api
                                .cancelRefund(id)
                                .then((res) => {
                                    if (res.code === 0) {
                                        uni.showToast({
                                            title: "取消成功",
                                            icon: "none"
                                        });
                                        this.resetData();
                                        this.fetchRefunds();
                                    } else {
                                        uni.showToast({
                                            title: res.msg || "取消失败",
                                            icon: "none"
                                        });
                                    }
                                })
                                .catch(() => {
                                    uni.showToast({
                                        title: "取消失败，请重试",
                                        icon: "none"
                                    });
                                });
                        }
                    }
                });
            },
            fetchRefunds(isRefresh = false) {
                if (this.loading || !this.hasMore) return;
                this.loading = true;

                let params = {
                    pageNo: this.pageIndex,
                    pageSize: this.pageSize,
                };

                this.$api
                    .getRefundList(params)
                    .then((res) => {
                        if (res.code === 0) {
                            const data = res.data.list || [];
                            this.refunds = [...this.refunds, ...data];
                            this.hasMore = data.length >= this.pageSize;
                        } else {
                            uni.showToast({
                                title: res.msg || "加载失败",
                                icon: "none"
                            });
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                        if (isRefresh) {
                            this.refresherTriggered = false;
                        }
                    });
            },
            // 格式化退款创建时间
            formatRefundCreateTime(timestamp) {
                if (!timestamp) return '';
                
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            getRefundStatusText(status) {
                // 参考 yudao-mall-uniapp/pages/order/aftersale/list 页面的状态映射
                if (status === 10) {
                    return '申请售后';
                }
                if (status === 20) {
                    return '商品待退货';
                }
                if (status === 30) {
                    return '商家待收货';
                }
                if (status === 40) {
                    return '等待退款';
                }
                if (status === 50) {
                    return '退款成功';
                }
                if (status === 61) {
                    return '买家取消';
                }
                if (status === 62) {
                    return '商家拒绝';
                }
                if (status === 63) {
                    return '商家拒收货';
                }
                return '未知状态';
            },
            getRefundStatusDescription(refund) {
                // 参考 yudao-mall-uniapp/sheep/hooks/useGoods.js 的状态描述映射
                if (refund.status === 10) {
                    return '退款申请待商家处理';
                }
                if (refund.status === 20) {
                    return '请退货并填写物流信息';
                }
                if (refund.status === 30) {
                    return '退货退款申请待商家处理';
                }
                if (refund.status === 40) {
                    return '等待退款';
                }
                if (refund.status === 50) {
                    return '退款成功';
                }
                if (refund.status === 61) {
                    return '退款关闭';
                }
                if (refund.status === 62) {
                    return `商家不同意退款申请，拒绝原因：${refund.auditReason || '无'}`;
                }
                if (refund.status === 63) {
                    return `商家拒绝收货，不同意退款，拒绝原因：${refund.auditReason || '无'}`;
                }
                return '未知状态';
            },
            onReachBottom() {
                if (!this.hasMore || this.loading) return;
                this.pageIndex++;
                this.fetchRefunds();
            },
            onPageScroll(e) {
                this.scrollTop = e.scrollTop;
            }
        },
        onLoad() {
            this.fetchRefunds();
        }
    };
</script>

<style>
    .container {
        padding-bottom: env(safe-area-inset-bottom);
    }

    .tui-refund-list {
        margin-top: 0;
    }

    .tui-refund-item {
        margin-top: 20rpx;
        border-radius: 10rpx;
        overflow: hidden;
    }

    .tui-refund-header {
        width: 100%;
        font-size: 28rpx;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
    }
    
    .tui-refund-info {
        display: flex;
        flex-direction: column;
        gap: 4rpx;
    }
    
    .tui-refund-number {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
    }
    
    .tui-refund-time {
        font-size: 24rpx;
        color: #999;
    }

    .tui-refund-status {
        color: #888;
        font-size: 26rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        justify-content: center;
    }
    
    .tui-refund-status-content {
        font-size: 26rpx;
        color: #E41F19;
        font-weight: 500;
    }

    .tui-goods-item {
        width: 100%;
        padding: 20rpx 30rpx;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
    }

    .tui-goods-img {
        width: 180rpx;
        height: 180rpx;
        display: block;
        flex-shrink: 0;
    }

    .tui-goods-center {
        flex: 1;
        padding: 20rpx 8rpx;
        box-sizing: border-box;
    }

    .tui-goods-name {
        max-width: 310rpx;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        font-size: 26rpx;
        line-height: 32rpx;
    }

    .tui-goods-attr {
        font-size: 22rpx;
        color: #888888;
        line-height: 32rpx;
        padding-top: 20rpx;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        line-clamp: 2;
    }

    .tui-price-right {
        text-align: right;
        font-size: 24rpx;
        color: #888888;
        line-height: 30rpx;
        padding-top: 20rpx;
    }

    .tui-refund-info-detail {
        padding: 20rpx 30rpx;
        background: #f8f8f8;
    }

    .tui-refund-type {
        font-size: 24rpx;
        color: #333;
        margin-bottom: 10rpx;
    }

    .tui-refund-reason {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
    }

    .tui-refund-description {
        font-size: 24rpx;
        color: #666;
    }

    .tui-refund-status-desc {
        font-size: 24rpx;
        color: #E41F19;
        margin-bottom: 10rpx;
        font-weight: 500;
    }

    .tui-refund-btn {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        background: #fff;
        padding: 10rpx 30rpx 20rpx;
        box-sizing: border-box;
    }

    .tui-btn-ml {
        margin-left: 20rpx;
    }
</style>